package com.my.ribbon.rule;

import com.my.core.util.INetUtil;
import com.my.core.util.spring.BeanUtil;
import com.my.ribbon.predicate.MetadataAwarePredicate;
import com.my.ribbon.support.CustomRibbonRuleProperties;
import com.netflix.loadbalancer.Server;
import org.springframework.util.ObjectUtils;
import org.springframework.util.PatternMatchUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @author timo 2021/3/23
 */
public class MetadataAwareRule extends DiscoveryEnabledRule {
    public MetadataAwareRule() {
        super(MetadataAwarePredicate.INSTANCE);
    }

    @Override
    public List<Server> filterServers(List<Server> serverList) {
        CustomRibbonRuleProperties ribbonProperties = (CustomRibbonRuleProperties) BeanUtil.getBean(CustomRibbonRuleProperties.class);
        List<String> priorIpPattern = ribbonProperties.getPriorIpPattern();
        String hostIp = INetUtil.getHostIp();
        boolean hasPriorIpPattern = !priorIpPattern.isEmpty();
        String[] priorIpPatterns = (String[])priorIpPattern.toArray(new String[0]);
        List<Server> priorServerList = new ArrayList();
        Iterator var8 = serverList.iterator();

        while(var8.hasNext()) {
            Server server = (Server)var8.next();
            String host = server.getHost();
            if (ObjectUtils.nullSafeEquals(hostIp, host)) {
                return Collections.singletonList(server);
            }

            if (hasPriorIpPattern && PatternMatchUtils.simpleMatch(priorIpPatterns, host)) {
                priorServerList.add(server);
            }
        }

        if (!priorServerList.isEmpty()) {
            return priorServerList;
        } else {
            return Collections.unmodifiableList(serverList);
        }
    }
}
